package org.dochandler.dao.derby;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.dochandler.config.DHConfig;
import org.dochandler.dao.OfficerDAO;
import org.dochandler.service.domain.Officer;
import org.dochandler.service.domain.Rank;
import org.dochandler.service.exception.DatabaseException;

public class DerbyOfficerDAO implements OfficerDAO {

	private Connection conn;
	private String derbyUrl;
	private String derbyDriver;
	
	static public void main(String[] args) throws Exception {
		DerbyOfficerDAO dao = new DerbyOfficerDAO();
		List<Officer> lo = dao.findAll();
		for (Officer o : lo) {
			System.out.println("Id: " + o.getId() + " - Name: " + o.getName() + " - Rank: " + o.getRank());
		}
	}
	

	public DerbyOfficerDAO() {
		if (conn == null) {
			this.derbyUrl = DHConfig.getString("db_url");
			this.derbyDriver = DHConfig.getString("db_driver");
	
			try {
				Class.forName(derbyDriver).newInstance();
				conn = DriverManager.getConnection(derbyUrl);
			} catch (Exception e) {
				throw new DatabaseException("Could not connect to the database", e);
			}
		}
	}

	@Override
	public Officer findById(Long entityId) {
		return null;
	}

	@Override
	public List<Officer> findAll() {
		List<Officer> list = new ArrayList<Officer>();
		
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM OFFICERS");
			
			while (rs.next()) {
				int i=1;
				Long id = rs.getLong(i++);
				String officerName = rs.getString(i++);
				
				String rankName = rs.getString(i++);
				Rank rank = Rank.fromValue(rankName);
				
				list.add( new Officer(id, officerName, rank) );
			}
			
		} catch (SQLException e) {
			throw new DatabaseException("Could not execute find all officers", e);
		}
		
		return list;
	}

	@Override
	public boolean create(Officer entity) {
		return false;
	}

	@Override
	public boolean delete(Officer entity) {
		return false;
	}

	@Override
	public boolean update(Officer entity) {
		return false;
	}

}
